package com.myrice;

import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.myrice.remote.DefaultObjectConnector;
import com.myrice.remote.Exportor;
import com.myrice.remote.spring.SpringBeansExportor;

public class Startup {
	private static DefaultObjectConnector conector;

	public static DefaultObjectConnector getConector() {
		return conector;
	}

	public static void main(String[] args) throws IOException {
		configureLog4j();

		String host = "0.0.0.0";
		int port = 9000;
		String beansLocation = "beans.xml";
		String exportLocation = "export.properties";

		if (args.length >= 1) {
			int index = args[0].indexOf(":");
			if (index != -1) {
				host = args[0].substring(0, index);
				port = Integer.parseInt(args[0].substring(index + 1));
			} else {
				port = Integer.parseInt(args[0]);
			}
		}
		if (args.length >= 2)
			beansLocation = args[1];
		if (args.length >= 3)
			exportLocation = args[2];

		conector = new DefaultObjectConnector(host, port);
		ApplicationContext beans = new FileSystemXmlApplicationContext(
				beansLocation);
		Exportor exportor = new SpringBeansExportor(beans, exportLocation);
		conector.setExportor(exportor);
		conector.start();

		String portPath = System.getProperty("write.port");
		if (portPath != null) {
			FileWriter out = null;
			try {
				out = new FileWriter(portPath);
				out.write(String.valueOf(port));
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
		}
	}

	private static void configureLog4j() {
		String configFile = System.getProperty("log4j");
		if (configFile != null) {
			PropertyConfigurator.configure(configFile);
		}
	}
}
